1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import collections
preferred_rankings_men = { 'ryan': ['lizzy', 'sarah', 'zoey', 'daniella'], 'josh': ['sarah', 'lizzy', 'daniella', 'zoey'], 'blake': ['sarah', 'daniella', 'zoey', 'lizzy'], 'connor': ['lizzy', 'sarah', 'zoey', 'daniella'] }
preferred_rankings_women = { 'lizzy': ['ryan', 'blake', 'josh', 'connor'], 'sarah': ['ryan', 'blake', 'connor', 'josh'], 'zoey': ['connor', 'josh', 'ryan', 'blake'], 'daniella': ['ryan', 'josh', 'connor', 'blake'] }
tentative_engagements = []
free_men = []
def init_free_men(): '''Initialize the arrays of women and men to represent that they're all initially free and not engaged''' for man in list(preferred_rankings_men): free_men.append(man)
def begin_matching(man): '''Find the first free woman available to a man at any given time'''
print("DEALING WITH %s"%(man)) for woman in preferred_rankings_men[man]:
taken_match = [couple for couple in tentative_engagements if woman in couple]
if (len(taken_match) == 0): tentative_engagements.append([man, woman]) free_men.remove(man) print('%s is no longer a free man and is now tentatively engaged to %s'%(man, woman)) break
elif (len(taken_match) > 0): print('%s is taken already..'%(woman))
current_guy = preferred_rankings_women[woman].index(taken_match[0][0]) potential_guy = preferred_rankings_women[woman].index(man)
if (current_guy < potential_guy): print('She\'s satisfied with %s..'%(taken_match[0][0])) else: print('%s is better than %s'%(man, taken_match[0][0])) print('Making %s free again.. and tentatively engaging %s and %s'%(taken_match[0][0], man, woman)) free_men.remove(man)
free_men.append(taken_match[0][0])
taken_match[0][0] = man break
def stable_matching(): '''Matching algorithm until stable match terminates''' while (len(free_men) > 0): for man in free_men: begin_matching(man)
def main(): init_free_men() print(free_men) stable_matching() print(tentative_engagements)
main()
|